from tortoise.models import Model
from tortoise import fields
from pydantic import BaseModel, Field
from datetime import datetime
from typing import Optional  # 确保正确导入


# Tortoise-ORM 模型
class Comment(Model):
    comment_id = fields.IntField(pk=True)  # 评论ID（主键）
    content = fields.TextField()  # 评论内容
    created_at = fields.DatetimeField(auto_now_add=True)  # 创建时间
    top = fields.IntField(default=0)  # 点赞数（默认0）

    # 多对一关系：多个评论属于一个用户
    author = fields.ForeignKeyField(
        "models.Student",
        related_name="comments",
        on_delete=fields.SET_NULL,  # 用户删除后保留评论
        null=True
    )

    # 多对一关系：多个评论属于一个讨论
    discussion = fields.ForeignKeyField(
        "models.Discussion",
        related_name="comments",
        on_delete=fields.CASCADE  # 讨论删除时级联删除评论
    )

    class Meta:
        table = "comments"
        ordering = ["-top", "-created_at"]  # 默认按点赞数降序，时间降序


# ---------- Pydantic 模型 ----------


    class Config:
        from_attributes = True